package sqlToGUI.sqlRetrievalAlgorithms;


import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.GregorianCalendar;

import sqlToGUI.charts.helperUtilities.TelemetryDataEntry;
import sqlToGUI.sqlRetrievalAlgorithms.AbstractDataRetrievalAlgorithm;
import sqlToGUI.sqlRetrievalAlgorithms.SQLDataRetrievalAlgorithm;


/**This is simple test for the GUI - checks to see if the listeners
 * are working correctly when data is updated into the buffer by this
 * algorithm
 * Two test cases included: - data sent to buffer is a simple integer
 * 							- data sent to buffer is a simple value 
 *                            taken from the SQL database 
 *                            (this also tests the database storage)*/
public class Alg_Test extends AbstractDataRetrievalAlgorithm  
implements SQLDataRetrievalAlgorithm {

	/**Variable indicating whether the test data is created by
	 * initialization of simple variables or if it is coming from
	 * the database */
	private boolean dataFromSQL = false;
	private int counter = 0;

	/**Class constructor */
	public Alg_Test(TelemetryDataEntry[] list){
		super();
		this.list = list;
	}

	/**Access the database and update data in the buffer */
	@SuppressWarnings("deprecation")
	public void updateData(){
		if(dataFromSQL){

			/**Use the timer for accessing the buttom rows with
			 * the most recent timestamp - set this value back a few 
			 * seconds to avoid returning null values for results
			 * that have not yet entered the database */
			timeNow = new GregorianCalendar();
			Timestamp ts =  new Timestamp(super.timeNow.getTimeInMillis());
			ts.setSeconds(ts.getSeconds()-setBack);

			/**Execute the query */
			try {
				super.statement.clearBatch();
				super.query = "SELECT A1.VoltageIn1 FROM SolarArray A1 " + " " +
				"WHERE A1.Timestamp IN " +
				"(SELECT cast(timestamp as char) timestamp " +
				"FROM SolarArray " +
				"WHERE timestamp > '" 
				+ ts.toString().substring(0, 19) + "');";

				super.rs = super.statement.executeQuery(super.query);
				rs.next();
				list[0].updateData(0, super.rs.getDouble(1));
				super.rs.close();

			} catch (SQLException e) {
				System.out.println("Alg_ArrayVoltage: Failed to read data " +
				"from database after query failure ");
				list[0].updateData(0, 0);
				list[1].updateData(0, 0);
				System.out.println("Query: " + query);
			} catch (NullPointerException e) {
				System.out.println("Alg_ArrayVoltage: Failed to read data " +
				"from database or no input found ");
				list[0].updateData(0, 0);
				list[1].updateData(0, 0);
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("Alg_ArrayVoltage: More or less buffers" +
				" have been expected for the algorithm");
				list[0].updateData(0, 0);
				list[1].updateData(0, 0);
			}	
		}
		
		else {
			list[0].updateData(0, counter);
			counter++;
		}
		
	}	
}
